'use strict';
//http://www.material-ui.com/#/components/select-field


var ibc = {};
var chaincode = {};
var async = require('async');
//var Fiber = require('fibers');
var deasync = require('deasync');
var atob = require('atob');

class ws4rest{
}

export const wsRest = new ws4rest();

wsRest.setup=function(sdk, cc){
	ibc = sdk;
	chaincode = cc;
}

wsRest.parserBlock=function(binfo,hi){
		var rbinfo = {};
		if(binfo.transactions == null){
			rbinfo.blockheight = hi;
			rbinfo.created = this.formatDate(binfo.nonHashData.localLedgerCommitTimestamp.seconds * 1000, '%M-%d-%Y %I:%m%p') + ' UTC';
			rbinfo.uuid = '';
			rbinfo.type = '';
			rbinfo.ccid = '';
			rbinfo.payload = '';
		}else{
			var ccid = this.formatCCID(binfo.transactions[0].type, binfo.transactions[0].uuid, atob(binfo.transactions[0].chaincodeID));
			rbinfo.blockheight = hi;
			rbinfo.created = this.formatDate(binfo.transactions[0].timestamp.seconds * 1000, '%M-%d-%Y %I:%m%p') + ' UTC';
			rbinfo.uuid = this.formatUUID(binfo.transactions[0].type, binfo.transactions[0].uuid);
			rbinfo.type = this.formatType(binfo.transactions[0].type);
			rbinfo.ccid = ccid;
			var tmpstr = '';
			//var transactions = rbinfo.transactions;
			//console.log('get block transactions='+JSON.stringify(rbinfo));
			var len = 100;
			for(var i = 0; i < 100; i++){
			// for (var transitem in rbinfo.transactions) {
			 //for(var i = 0; i<rbinfo.transactions.length;  i++){
				 var transitem = null;
				 if(binfo.transactions[i] == null){
					break;
				 }
				transitem =  binfo.transactions[i];
				var ccid1 = this.formatCCID(transitem.type, transitem.uuid, atob(transitem.chaincodeID));
				var payload = atob(transitem.payload);
				tmpstr = tmpstr + this.formatPayload(payload, ccid1);
			}
			//var payload = atob(binfo.transactions[0].payload);
			//tmpstr = tmpstr + this.formatPayload(payload, ccid);
			rbinfo.payload = tmpstr;
		}
		return rbinfo;
	}


	 wsRest.formatCCID=function(i, uuid, ccid){								//flip uuid and ccid if deploy, weird i know
		if(i == 1) return ccid;
		return ccid;
	}

	wsRest.formatUUID=function(i, uuid){									//blank uuid if deploy, its just ccid again
		if(i == 1) return '-';
		return uuid;
	}

	wsRest.formatType=function(i){											//spell out deploy or invoke
		if(i == 1) return 'deploy';
		if(i == 3) return 'invoke';
		return i;
	}

	wsRest.formatPayload=function(str, ccid){								//create a sllliiiggghhhtttlllllyyy better payload name from decoded payload
		var func = ['init',  'write',  'open_trade', 'perform_trade'];
		str =  str.substring(str.indexOf(ccid) + ccid.length + 4);
		for(var i in func){
			if(str.indexOf(func[i]) >= 0){
				return func[i] + ': ' + str.substr(func[i].length);
			}
		}
		return str;
	}

	wsRest.formatDate=function(date, fmt) {
		date = new Date(date);
		function pad(value) {
			return (value.toString().length < 2) ? '0' + value : value;
		}
		return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
			var tmp;
			switch (fmtCode) {
			case 'Y':								//Year
				return date.getUTCFullYear();
			case 'M':								//Month 0 padded
				return pad(date.getUTCMonth() + 1);
			case 'd':								//Date 0 padded
				return pad(date.getUTCDate());
			case 'H':								//24 Hour 0 padded
				return pad(date.getUTCHours());
			case 'I':								//12 Hour 0 padded
				tmp = date.getUTCHours();
				if(tmp === 0) tmp = 12;				//00:00 should be seen as 12:00am
				else if(tmp > 12) tmp -= 12;
				return pad(tmp);
			case 'p':								//am / pm
				tmp = date.getUTCHours();
				if(tmp >= 12) return 'pm';
				return 'am';
			case 'P':								//AM / PM
				tmp = date.getUTCHours();
				if(tmp >= 12) return 'PM';
				return 'AM';
			case 'm':								//Minutes 0 padded
				return pad(date.getUTCMinutes());
			case 's':								//Seconds 0 padded
				return pad(date.getUTCSeconds());
			case 'r':								//Milliseconds 0 padded
				return pad(date.getUTCMilliseconds(), 3);
			case 'q':								//UTC timestamp
				return date.getTime();
			default:
				throw new Error('Unsupported format code: ' + fmtCode);
			}
		});
	}
	wsRest.getBlockStat4Sync=function(){
		var retObject = null;
    	var isFinish = false;
		ibc.chain_stats(function(e,data){
            if(e != null){
                console.log(e);
            }else{
				retObject = data;
			}
        	isFinish = true;
		}
		)
		while(retObject == null && !isFinish){
        	deasync.runLoopOnce();
		}
    	return retObject;
	}

	wsRest.getBlockInfo4Sync=function(bnumber){
		var retObject = null;
    	var isFinish = false;
		ibc.block_stats(bnumber,function(e,data){
            if(e != null){
                console.log(e);
            }else{
				retObject = data;
			}
        	isFinish = true;
		}
		)
		while(retObject == null && !isFinish){
        	deasync.runLoopOnce();
		}
    	return retObject;
	}

wsRest.getBlocks = function(e,data){
	var myArray=[];
	var bstat = this.getBlockStat4Sync();
	if(bstat != null){
		var bheight = bstat.height;
		var i = 0;
		for( i = 0; i < bheight; i++){
			var binfo = this.getBlockInfo4Sync(i);
			//if(binfo.transactions != null){
				binfo = this.parserBlock(binfo,i+1);
				myArray.push(binfo);
			//}
		}
	}
	return myArray;

	
}


wsRest.registerUser4Sync=function(userid,pwd){
		var retObject = null;
    	var isFinish = false;
		ibc.register(0, userid, pwd, 1, function(e,data){
            if(e != null){
                console.log(e);
            }else{
				retObject = data;
			}
        	isFinish = true;
		}
		)
		while(retObject == null && !isFinish){
        	deasync.runLoopOnce();
		}
    	return retObject;
	}
wsRest.registerUser = function(userid,pwd){
	var ruser = null;
	ruser = this.registerUser4Sync(userid,pwd);
	return ruser;

	
}


wsRest.getQuery4Sync=function(qdata){
		var retObject = null;
    	var isFinish = false;
		
		chaincode.query.read([qdata],function(e,data){
            if(e != null){
                console.log(e);
            }else{
				retObject = data;
			}
        	isFinish = true;
		}
		)
		while(retObject == null && !isFinish){
        	deasync.runLoopOnce();
		}
    	return retObject;
	}

wsRest.getQuery = function(qdata){
	var myts = null;
	myts = this.getQuery4Sync(qdata)
	return myts;

	
}

wsRest.perform_trade_invoke4Sync=function(tradeData){
		var retObject = null;
    	var isFinish = false;
		console.log("start perform trade ... ...");
		var args = [tradeData.tradecustomid, tradeData.content];
		chaincode.invoke.perform_trade(args,function(e,data){
            if(e != null){
                console.log(e);
            }else{
				retObject = data;
			}
        	isFinish = true;
		}
		)
		while(retObject == null && !isFinish){
        	deasync.runLoopOnce();
		}
    	return retObject;
	}

wsRest.perform_trade_invoke = function(data){
	var ra = this.perform_trade_invoke4Sync(data);
	return ra;
	
	
}

